/**
 * Created by Administrator on 2017/7/14.
 */
import axios from 'axios'
import router from '../../router/index'
import {Message} from 'element-ui'
var urlConfig = require('../../../src/config');

let config = {
  method: 'get',
  baseURL: urlConfig.apiUrl
};

var httpAjax = axios.create(config);
httpAjax.interceptors.request.use(config => {
    let token = window.sessionStorage.getItem('token');
    if (token) {
      config.headers.Authorization = "Bearer " + token;
    }
    return config;
  },
  err => {
    return Promise.reject(err);
  });


//返回状态判断// 添加响应 拦截器
httpAjax.interceptors.response.use((res) => {
  if ((200 <= res.status && res.status < 300) && res.status != 204) {
    return res.data;
  } else {
    return Promise.reject(res.data);
  }
}, (error) => {
  // 对响应错误做点什么
  if (error.response) {
    if (error.response.status == 401) {
      router.replace({
        path: 'login',
        query: {redirect: router.currentRoute.fullPath}//登录成功后跳入浏览的当前页面
      })
    }else if(error.response.status == 422){

      Message.error(error.response.data.message);
    }
  }
  return Promise.reject(error);
});
//接口列表
export default {
  fetch: (url, config) => {
    return new Promise((resolve, reject) => {
      httpAjax(url, config)
        .then(response => {
          resolve(response);
        })
        .catch((error) => {
          reject(error)
        })
    })
  }
}
